"""
FastAPI应用程序主文件
"""
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
import time
import uvicorn
from .routes import router
from ..config import API_HOST, API_PORT, API_DEBUG

# 创建FastAPI应用
app = FastAPI(
    title="ROCm大模型推理API",
    description="基于ROCm的大语言模型推理API接口",
    version="1.0.0",
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 添加请求处理时间中间件
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response

# 添加路由
app.include_router(router)

# 根路由
@app.get("/", tags=["根路由"])
async def root():
    return {
        "message": "欢迎使用ROCm大模型推理API",
        "docs_url": "/docs",
        "redoc_url": "/redoc"
    }

# 健康检查
@app.get("/health", tags=["健康检查"])
async def health_check():
    return {"status": "healthy"}

# 异常处理
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    return JSONResponse(
        status_code=500,
        content={"message": f"发生错误: {str(exc)}"}
    )

# 启动服务器
def start_server():
    """启动API服务器"""
    uvicorn.run(
        "src.api.app:app",
        host=API_HOST,
        port=API_PORT,
        reload=API_DEBUG
    )

if __name__ == "__main__":
    start_server()